package com.sevenday.threadlimit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @类名: SemaphoreLimit
 * @描述: 信号量限流[控制并发数量 ]
 * @作者: zfh;
 * @邮箱：806970740@qq.com
 * @时间: 2017年9月2日 下午11:23:02
 */
public class TimeWindowLimiter {
    /**
     * 进行初始化的过期的缓存的设置
     */
    private int limit = 1000;
    private boolean isend = true;
    private LoadingCache<Long, AtomicLong> counter =
            CacheBuilder.newBuilder()
                    .expireAfterWrite(2, TimeUnit.SECONDS)
                    .build(new CacheLoader<Long, AtomicLong>() {
                        @Override
                        public AtomicLong load(Long seconds) throws Exception {
                            return new AtomicLong(0);
                        }
                    });
    public void process() {
        while (isend) {
            //得到当前秒
            long currentSeconds = System.currentTimeMillis() / 1000;
            try {
                if (counter.get(currentSeconds).incrementAndGet() > limit) {
                    System.out.println("限流了:" + currentSeconds);
                    continue;
                }
                //进行业务逻辑的处理
            } catch (ExecutionException e) {
                e.printStackTrace();
                isend = false;
            }

        }

    }
}
